package com.eazytec.efs.utils;

import com.eazytec.efs.common.Constants;
import com.eazytec.efs.common.ProgressDownloader;
import com.eazytec.efs.common.ProgressResponseBody;
import com.eazytec.efs.common.ResultMsg;
import org.apache.log4j.Logger;

import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 测试下载 断点续传 进度 回调函数等
 *
 * @author Zhaozx
 * @create 2017-10-13 8:37
 **/
public class DownloadUtils implements ProgressResponseBody.ProgressListener {

    static Logger logger = Logger.getLogger(DownloadUtils.class);

    static long breakPoints;
    static ProgressDownloader downloader;
    static File file;
    static long totalBytes;
    static long contentLength;
    static String PACKAGE_URL = "https://58.215.198.210:8443/EFS_test/2.pdf";

    public static long getHttpFileLength(String urlStr) throws Exception {
        URL url = new URL(urlStr);
        HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
        urlcon.setRequestProperty("Accept-Encoding", "identity");
        contentLength = urlcon.getContentLength();
        logger.info("get filelength: " + contentLength);
        return contentLength;
    }

    public static ResultMsg downLoad(String url, String savePath, ResultMsg resultMsg) {
        try {

            PACKAGE_URL = url;
            logger.info("start download...");
            contentLength = getHttpFileLength(PACKAGE_URL);

            // 新下载前清空断点信息
            breakPoints = 0L;

            String fileName  = url.substring(url.lastIndexOf("/") + 1);
            file = new File(savePath);
            if(!file.exists())
                file.mkdirs();
            file = new File(savePath + File.separator + fileName);

            downloader = new ProgressDownloader(PACKAGE_URL, file, new DownloadUtils(), resultMsg);

            //暂存信息
            resultMsg.getDownBean().setDownloader(downloader);
            resultMsg.getDownBean().setFile(file);
            resultMsg.getDownBean().setBreakPoints(breakPoints);
            resultMsg.getDownBean().setContentLength(contentLength);

            downloader.download(0L, contentLength);

        } catch (Exception e) {
            e.printStackTrace();
            resultMsg.setCode(Constants.fail_code);
            resultMsg.setMsg(resultMsg.getMsg() + "\n" + e.getMessage());
        }
        return resultMsg;
    }

    public static void pause(ResultMsg resultMsg){
        logger.info("pause...");
        downloader.pause();
        // 存储此时的totalBytes，即断点位置。
        breakPoints = totalBytes;
        resultMsg.getDownBean().setBreakPoints(totalBytes);
    }

    public static void continueDownload(ResultMsg resultMsg){
        logger.info("continue...");
        resultMsg.getDownBean().getDownloader().download(resultMsg.getDownBean().getBreakPoints(), resultMsg.getDownBean().getContentLength());
//        downloader.download(breakPoints, contentLength);
    }


    @Override
    public void onPreExecute(long aa) {
//        // 文件总长只需记录一次，要注意断点续传后的contentLength只是剩余部分的长度
//        if (contentLength == 0L) {
//            contentLength = aa;
//            System.out.println("onPreExecute: "+(int) (contentLength / 1024));
//        }
    }

    @Override
    public void update(long aa, boolean done) {
        // 注意加上断点的长度
        totalBytes = aa + breakPoints;
        logger.info("totalBytes: " + totalBytes + " ,aa: " + aa + " , breakPoints: " + breakPoints + " , contentLength: " + contentLength + " ,progress: " + (float) (((float) (aa + breakPoints)) / ((float) (contentLength))));
    }
}
